const router = require('koa-router')()
const { exec } = require('../utils/exec')
const { SuccessModel, FailModel } = require('../utils/resModel')
const { getPassword } = require('../utils/crypto')
const jwt = require('jsonwebtoken')
const secretKey = 'Wde123_.'

router.prefix('/users')

router.post('/login', async function (ctx, next) {
  const { username, password } = ctx.request.body
  const loginData = await exec(
    `select * from users where username=? and password=?`,
    [username, getPassword(password)]
  )
  console.log('loginData:', loginData[0])
  const token = jwt.sign(
    {
      id: loginData[0].id,
      username: loginData[0].username,
    },
    secretKey,
    { expiresIn: '10min' }
  )

  ctx.body = new SuccessModel({ token })
})

router.post('/register', async (ctx, next) => {
  const { username, password, avatar, nickname, gender } = ctx.request.body
  try {
    const sql = `insert into users (username, password, nickname, avatar,gender) 
    values (?,?,?,?, ?)`
    const registerData = await exec(sql, [
      username,
      getPassword(password),
      nickname,
      avatar,
      gender,
    ])
    ctx.body = new SuccessModel(registerData)
  } catch (err) {
    ctx.body = new FailModel(registerData)
  }
})

// 用户查询接口

router.get('/list', async (ctx, next) => {
  const { page = 1, size = 2 } = ctx.query
  const { token } = ctx.request.headers
  try {
    jwt.verify(token, secretKey)
    const userList = await exec(`select * from users limit ? offset ?`, [
      size * 1,
      (page - 1) * size * 1,
    ])
    ctx.body = new SuccessModel(userList)
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})
// select * from users where username like '%镇%' and password ='123';

// 模糊搜索接口
router.get('/search', async (ctx, next) => {
  const { keywords } = ctx.query
  try {
    const sql = `select * from users where username like '%${keywords}%'`
    const data = await exec(sql)
    ctx.body = new SuccessModel(data)
  } catch (err) {
    ctx.body = new FailModel(err)
  }
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router
